<template>
  <div class="login-account">
    <el-form ref="ruleFormRef" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="账号" prop="name">
        <el-input v-model="form.name" clearable />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" clearable show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
import { useStore } from 'vuex';
import type { FormInstance, FormRules } from 'element-plus';

import cacheUtils from '@/utils/local';

export default defineComponent({
  setup() {
    const store = useStore();
    const ruleFormRef = ref<FormInstance>();
    const form = reactive({
      name: cacheUtils.getCache('name') ?? 'coderwhy',
      password: cacheUtils.getCache('password') ?? '123456',
    });
    const rules = reactive<FormRules>({
      name: [
        {
          required: true,
          message: '请输入账号！',
          trigger: 'blur',
        },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
      ],
      password: [
        {
          required: true,
          message: '请输入密码！',
          trigger: 'blur',
        },
      ],
    });

    const submit = async (
      formEl: FormInstance | undefined,
      cache?: boolean,
    ) => {
      if (!formEl) return;
      await formEl.validate((valid, fields) => {
        // console.log('1111');
        if (valid) {
          // console.log('submit!');
          if (cache) {
            // console.log(form.name, form.password);
            cacheUtils.setCache('name', form.name);
            cacheUtils.setCache('password', form.password);
          }

          store.dispatch('LoginModule/accountLoginAction', { ...form });
        } else {
          console.log('error submit!', fields);
          cacheUtils.deleteCache('account');
          cacheUtils.deleteCache('password');
        }
      });
    };

    return {
      ruleFormRef,
      form,
      rules,
      submit,
    };
  },
});
</script>

<style scoped></style>
